// CHrkExport.cpp : Defines the entry point for the DLL application.
//

#include "stdafx.h"

#include "HRKStream.h"
#include "HRKExportApp.h"
#include "HRKExportClassDesc.h"


#ifndef _MFC_BUILD

extern ClassDesc2* GetIGameExporterDesc();

HINSTANCE hInstance;
int controlsInit = FALSE;

BOOL WINAPI DllMain(HINSTANCE hinstDLL,ULONG fdwReason,LPVOID lpvReserved)
{
	hInstance = hinstDLL;				// Hang on to this DLL's instance handle.
	theApp.m_hInstance = hInstance;

	if (!controlsInit) {
		controlsInit = TRUE;
		InitCustomControls(hInstance);	// Initialize MAX's custom controls
		InitCommonControls();			// Initialize Win95 controls
	}
			
	return (TRUE);
}

#endif

HRKEXPORT_API const TCHAR* LibDescription()
{
	return theApp.LoadString( IDS_LIBDESCRIPTION );
}

HRKEXPORT_API int LibNumberClasses()
{
	return 1;
}

HRKEXPORT_API ClassDesc* LibClassDesc(int i)
{
	switch(i) 
	{
		case 0: return GetHRKExportDesc();
		default: return 0;
	}
}

HRKEXPORT_API ULONG LibVersion()
{
	return VERSION_3DSMAX;
}

TCHAR* CHrkExportApp::LoadString( int id )
{
	TCHAR* buf = (TCHAR*)AllocMemory( sizeof(TCHAR)* 256 );
	buf[0] = 0;	
	::LoadString(m_hInstance, id, buf, sizeof(buf));
	return buf;	
}

void* CHrkExportApp::AllocMemory( int size )
{
	void* ptr = malloc( size );
	m_MemoryPtrPool.push_back( ptr );
	return ptr;
}

void CHrkExportApp::FreeMemory( void* ptr )
{
	free( ptr );
}

int CHrkExportApp::ExitInstance()
{
	//Clean the Memeory Ptr Pool
	int nPtr = (int)m_MemoryPtrPool.size();
	
	for( int i = 0;i< nPtr;i++)
	{
		FreeMemory( m_MemoryPtrPool[i] );
	}

	m_MemoryPtrPool.clear();

#ifdef _MFC_BUILD
	return CWinApp::ExitInstance();
#else
	return 0;
#endif

}

unsigned int CALLBACK background_func( void * p);

BOOL CHrkExportApp::InitInstance()
{
	// TODO: Add your specialized code here and/or call the base class

	BOOL ret = CWinApp::InitInstance();

	_AFX_THREAD_STATE* stat = AfxGetThreadState();
	memcpy(&m_stat,stat,sizeof(_AFX_THREAD_STATE));

	return ret;
	//return TRUE;
}


HINSTANCE CHrkExportApp::LoadAppLangResourceDLL()
{
	TCHAR szPath[MAX_PATH];
	LPTSTR pszExtension;

	int ret = ::GetModuleFileName(m_hInstance, szPath, MAX_PATH);
	if(ret == 0 || ret == MAX_PATH)
	{
		ASSERT(FALSE);
		return NULL;
	}

	HINSTANCE h =  ::LoadLibrary(szPath);

	return h;
}

void CHrkExportApp::MessageBoxV( const TCHAR* caption,const TCHAR* fmt,...)
{
	va_list ap;

	va_start( ap,fmt);
	int n = _vsctprintf( fmt,ap);
	va_end( ap );

	TCHAR* buff = (TCHAR*)malloc( sizeof(TCHAR)* ( n + 1 ));

	va_start( ap,fmt);
	_vstprintf( buff,fmt,ap );
	va_end( ap );


	::MessageBox( 0,buff,caption,0);

	free( buff );
}

#pragma init_seg(compiler)
CHrkExportApp theApp;